package com.caiyi.financial.nirvana.sms.gateway.http;

import com.caiyi.financial.nirvana.sms.entity.SmsReceiveMessage;
import com.caiyi.financial.nirvana.sms.enums.ReturnCodeEnum;
import com.caiyi.financial.nirvana.sms.enums.SmsMsgStatusEnum;
import com.caiyi.financial.nirvana.sms.jedis.JedisKey;
import com.caiyi.financial.nirvana.sms.jedis.JedisService;
import com.caiyi.financial.nirvana.sms.queue.NotifyQueueEntity;
import com.caiyi.financial.nirvana.sms.queue.ReceiveMsgQueueEntity;
import com.caiyi.financial.nirvana.sms.queue.SendQueueEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;


/**
 * \* User: ywg
 * \* 传计通道 支持行业，营销
 * \
 */
public class ChuanJiGateway extends BaseGateway {
    private static final Logger logger = LoggerFactory.getLogger(ChuanJiGateway.class);

    @Override
    public void sendMessage(SendQueueEntity entity) {
        int status = SmsMsgStatusEnum.REQUEST_FAIL.index;
        String result = "";
        try {
            Map param = buildParam(entity);
            String response = doPostGb2312(info.getServerAddr(), param);
            if (Objects.isNull(response)) {
                result = "网关请求超时";
                return;
            }
            Integer value = Integer.valueOf(response);
            if (value > 0) {
                status = SmsMsgStatusEnum.REQUEST_SUCCESS.index;
            }
            result = response;
            logger.info("ChuanJiGateway send url : {}, params : {}, result : {}", info.getServerAddr(), param, response);
        } catch (Exception e) {
            logger.error("ChuanJiGateway sendMessage error ! ", e);
        } finally {
            this.handlerResponse(entity, result, status);
        }

    }


    private Map buildParam(SendQueueEntity entity) {
        Map<String, String> map = new HashMap<>();
        map.put("Account", info.getAccount());
        map.put("Password", info.getPassword());
        map.put("Phones", entity.getPhone());
        map.put("Channel", "1");
        map.put("Content", entity.getContent());
        return map;
    }

    @Override
    public boolean notifyStatus(NotifyQueueEntity entity) {
        return false;
    }

    @Override
    public boolean receiveMsg(ReceiveMsgQueueEntity entity) {
        return false;
    }

    //主动获取
    public boolean queryStatus() {
        try {
            Map<String, String> map = new HashMap<>();
            map.put("Account", info.getAccount());
            map.put("Password", info.getPassword());
            String url = info.getServerAddr().replace("SendSms.asp", "GetReport.asp");
            String jsonStr = doPost(url, map);
            if (Objects.isNull(jsonStr) || !jsonStr.contains("$$$$")) {
                logger.info("ChuanJiGateway queryStatus jsonStr is {} ", jsonStr);
                return false;
            }
            int status;
            for (String content : jsonStr.split("\\|\\|\\|\\|")) {
                status = SmsMsgStatusEnum.SEND_FAIL.index;
                String[] index = content.split("\\$\\$\\$\\$");
                //批次号
                String taskId = index[0];
                String messageId = JedisService.hget(JedisKey.SMS_REMOTE_ID_MESSAGE_ID, taskId + index[1]);
                if (Objects.isNull(messageId)) {
                    logger.info("  messageId is null  phone is {}", index[1]);
                }
                JedisService.hdel(JedisKey.SMS_REMOTE_ID_MESSAGE_ID, taskId + index[1]);
                //状态标志
                String statusFlag = index[4];
                if ("DELIVRD".equals(statusFlag)) {
                    status = SmsMsgStatusEnum.SEND_SUCCESS.index;
                }
                receiveReport(status, messageId, statusFlag);
            }
            logger.info("ChuanJiGateway queryStatus result is {}", jsonStr);
        } catch (Exception e) {
            logger.error("ChuanJiGateway queryStatus error ! ", e);
            return false;
        }
        return true;
    }


    //主动获取上行信息
    public boolean queryReceiveMsg() {
        try {
            Map<String, String> map = new HashMap<>();
            map.put("Account", info.getAccount());
            map.put("Password", info.getPassword());
            String url = info.getServerAddr().replace("SendSms.asp", "GetMessage.asp");
            String jsonStr = doPostGb2312(url, map);
            logger.info("ChuanJiGateway queryReceiveMsg  result : {}", jsonStr);
            if (Objects.isNull(jsonStr) || !jsonStr.contains("$$$$")) {
                logger.info("ChuanJiGateway queryReceiveMsg jsonStr is {} ", jsonStr);
                return false;
            }
            for (String context : jsonStr.split("\\|\\|\\|\\|")) {
                String[] strings = context.split("\\$\\$\\$\\$");
                SmsReceiveMessage smsReceiveMessage = new SmsReceiveMessage();
                smsReceiveMessage.setCreateTime(new Date());
                smsReceiveMessage.setPhone(strings[0]);
                smsReceiveMessage.setContent(strings[1]);
                smsReceiveMessage.setMessageId(strings[0]);
                smsReceiveMessage.setAccessNumber(info.getAccessNumber());
                receiveMessage(smsReceiveMessage);
            }
            return true;
        } catch (Exception e) {
            logger.error("ChuanJiGateway queryReceiveMsg error ! ", e);
        }
        return false;
    }

    @Override
    public int queryBalance() {
        try {
            Map<String, String> map = new HashMap<>();
            map.put("Account", info.getAccount());
            map.put("Password", info.getPassword());
            map.put("Channel", "1");
            String url = info.getServerAddr().replace("SendSms.asp", "GetBalance.asp");
            String jsonStr = doPost(url, map);
            return Integer.parseInt(jsonStr);
        } catch (Exception e) {
            logger.error("ChuanJiGateway queryBalance error ! ", e);
        }
        return 0;
    }

}
